<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true">
        <el-form-item label="职位搜索：">
          <el-input placeholder="请输入职位关键字" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="keyword ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" @click="addRole">添加角色</el-button>
      <el-table border style="margin: 10px 0" :data="aclRoleList">
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          type="index"
          label="#"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime"></el-table-column>
        <el-table-column label="操作" width="265px">
          <template #="{ row }">
            <el-button
              type="primary"
              icon="User"
              size="small"
              @click="setPermission(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="editRole(row)"
            >
              编辑
            </el-button>
            <el-button type="primary" icon="Delete" size="small" @click="removeRole(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="getRoleList"
        @size-change="changeSize"
      />
    </el-card>
    <el-dialog
      v-model="dialogFormVisible"
      :title="`${roleParams.id ? '更新' : '添加'}`"
      width="500"
    >
      <el-form :model="roleParams">
        <el-form-item label="职位名称">
          <el-input v-model="roleParams.roleName" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="rolePermission">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <el-tree
          style="max-width: 600px"
          :data="permissionList"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="hasPermissionArrId"
          :props="defaultProps"
          ref="treeRef"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="rolePermission = false">取消</el-button>
          <el-button type="primary" @click="savePermission">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  reqRoleList,
  reqRoleAddOrUpdate,
  reqRoleMenuList,
  reqRolePermission,
  reqDeleteRole
} from '@/api/acl/role/index'
import type { AclRole, MenuData } from '@/api/acl/role/type'
let pageNo = ref(1)
let pageSize = ref(5)
let keyword = ref('')
let total = ref(0)
let aclRoleList = ref<AclRole[]>([])
let roleParams = reactive<AclRole>({
  roleName: '',
})
let dialogFormVisible = ref(false)
onMounted(() => {
  getRoleList()
})

const getRoleList = (pager = 1) => {
  pageNo.value = pager
  reqRoleList(pageNo.value, pageSize.value, keyword.value).then((res) => {
    if (res.code == 200) {
      aclRoleList.value = res.data.records
      total.value = res.data.total
    }
  })
}
const search = () => {
  getRoleList()
  keyword.value = ''
}
const reset = () => {
  keyword.value = ''
  getRoleList()
}
const changeSize = () => {
  getRoleList()
}
const addRole = () => {
  Object.assign(roleParams, {
    roleName: '',
    id: '',
  })
  dialogFormVisible.value = true
}
const editRole = (row: AclRole) => {
  Object.assign(roleParams, row)
  dialogFormVisible.value = true
}
const saveRole = () => {
  reqRoleAddOrUpdate(roleParams).then((res) => {
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: roleParams.id ? '修改成功' : '添加成功',
      })
      dialogFormVisible.value = false
      getRoleList(roleParams.id ? pageNo.value : 1)
    } else {
      ElMessage({
        type: 'error',
        message: roleParams.id ? '修改失败' : '添加失败',
      })
    }
  })
}
let rolePermission = ref(false)
let permissionList = ref<MenuData[]>([])
let hasPermissionArrId = ref<number[]>([])
const treeRef = ref()
const defaultProps = {
  children: 'children',
  label: 'name',
}
const setPermission = (row: MenuData) => {
  Object.assign(roleParams, row)
  reqRoleMenuList(row.id).then((res) => {
    if (res.code == 200) {
      permissionList.value = res.data
      hasPermissionArrId.value = filterId(permissionList.value, [])
    }
  })
  rolePermission.value = true
}
const filterId = (allPermission: any, hasArr: any) => {
  allPermission.forEach((p: any) => {
    if (p.select && p.level == 4) {
      hasArr.push(p.id)
    }
    if (p.children && p.children.length > 0) {
      filterId(p.children, hasArr)
    }
  })
  return hasArr
}
const savePermission = () => {
  let currentLevelIdArr = treeRef.value.getCheckedKeys()
  let halfIdArr = treeRef.value.getHalfCheckedKeys()
  reqRolePermission(
    roleParams.id as number,
    currentLevelIdArr.concat(halfIdArr),
  ).then(res =>{
    console.log('',res);
    if(res.code == 200){
      ElMessage({
        type: 'success',
        message: '分配权限成功',
      })
      rolePermission.value = false
      window.location.reload()
    }
  })
}
const removeRole = (id:number) => {
  reqDeleteRole(id).then(res => {
    if(res.code ==200){
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getRoleList()
    }else{
      ElMessage({
        type: 'error',
        message: '删除失败',
      })
    }
  })
}
</script>
<script lang="ts">
export default {
  name: 'Role',
}
</script>
<style lang="scss"></style>
